#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, os, pygame
from pygame import *
from random import random
#other
import classes, assets, funcs
from classes import sd
from funcs import *
from assets import constr
#dicts
import structures, units, strings
from strings import*


class Main:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((sd.scrwidth, sd.scrheight))
        pygame.display.set_caption("Raseay")
        
        if sd.fullscr:
            pygame.display.set_mode((sd.scrwidth, sd.scrheight), pygame.FULLSCREEN)
        
        self.dev = 1 #devmode
        
        self.updateUs = pygame.sprite.Group()
        
        self.terrain = assets.terrain()

        self.cam = assets.camera()
        
        self.stage = 0
        self.operation = "None"
        self.selected = list()
        self.postmp = (-1,-1)
        
        self.lastid = 0 #i know SO LAME it is

#---------------------------time----------------------------------------
        self.czas = pygame.time.Clock()
        self.nexttick = pygame.time.get_ticks()
        self.nextpress = pygame.time.get_ticks()
#--------------------------teksty---------------------------------------
        self.Structs = structures.structs
        self.Units = units.units
        self.Strings = strings

        self.Ilosc = classes.Ilosc()
        self.Economy = classes.Economy()
        
        self.loop()
    
    def DrawUI(self):
        self.screen.blit(img("gfx/ui/paneltop.png"), (sd.scrwidth/2-640,0))
        self.screen.blit(img("gfx/ui/panelbottom.png"), (sd.scrwidth/2-640,sd.scrheight-256))
        
        #-------------------------minimap-------------------------------
        drawrects(self.cam.x*255.0/(self.terrain.xm*1.0)+sd.scrwidth/2-512+20, \
        self.cam.y*90.0/(self.terrain.ym*1.0)+sd.scrheight-256+145, \
        int(255/(self.terrain.xm/1024.0)), \
        int(90/(self.terrain.ym/768.0)), \
        (255,255,255, 25), self.screen)
        
        #-----------------------construction----------------------------
        funcs.pmenu = list() 
        x = 0
        y = 0
        for z in constr(self.stage):
            self.screen.blit(img(z[1]), (sd.scrwidth/2-512+750+51*x, sd.scrheight-256+145+45*y))
            funcs.pmenu.append(pygame.Rect(sd.scrwidth/2-512+750+51*x, sd.scrheight-256+145+45*y, 50,45))
            if x >= 4: #in fact, it allows to make 5 objects in one line
                y += 1
                x = 0
            else:
                x += 1
        
        
        #---------------------------text--------------------------------
        #-----------------------always bottom---------------------------
        printsur(12, str(self.Economy.credits), [255,255,255], "topleft", (sd.scrwidth/2-512+320,3), self.screen)
        printsur(12, str(self.Economy.metal), [255,255,255], "topleft", (sd.scrwidth/2-512+425,3), self.screen)
        printsur(12, str(self.Economy.energy), [255,255,255], "topleft", (sd.scrwidth/2-512+530,3), self.screen)
     
        ##---------------------------dev--------------------------------
        if self.dev:
            printsur(12, "Pos: "+str(pygame.mouse.get_pos()[0]+self.cam.x)+";"+str(pygame.mouse.get_pos()[1]+self.cam.y), [255,255,255], "topleft", (0,0), self.screen)
            printsur(12, "FPS: "+str(self.czas.get_fps()), [255,255,255], "topleft", (0,15), self.screen)
            printsur(12, "Operation: "+str(self.operation), [255,255,255], "topleft", (0,30), self.screen)
            printsur(12, "Screen width: "+str(sd.scrwidth), [255,255,255], "topleft", (0,45), self.screen)
            printsur(12, "Screen height: "+str(sd.scrheight), [255,255,255], "topleft", (0,60), self.screen)
            printsur(12, "Full screen: "+str(sd.fullscr), [255,255,255], "topleft", (0,75), self.screen)
                        
    def SelectInRect(self, newpos):
        toselect = drawrects(self.postmp[0]-self.cam.x, self.postmp[1]-self.cam.y, newpos[0]-self.postmp[0]+self.cam.x, newpos[1]-self.postmp[1]+self.cam.y, (0, 200, 0, 30), self.screen)
        for zz in self.updateUs:
            if ColRects(toselect, zz.rect):
                if not zz.canmove and len(self.selected):
                    return
                zz.hpbar = list()
                zz.hpbar.append(makeSurface(82, 6, (0,0,0,50)))
                zz.hpbar.append(makeSurface(80, 4, (0,255,0,70)))
                self.selected.append(zz.idn)
        
        
    def DrawHolo(self):
        #-------------------------selected------------------------------
        for obj in self.updateUs:
            for selected in self.selected:
                if selected == obj.idn:
                    self.screen.blit(obj.hpbar[0], (obj.rect.midtop[0]-41-self.cam.x, obj.rect.y-self.cam.y-5))
                    self.screen.blit(obj.hpbar[1], (obj.rect.midtop[0]-40-self.cam.x, obj.rect.y-self.cam.y-4))
   
    def EcoTick(self):
        if self.nexttick <= pygame.time.get_ticks():
            self.Economy.credits += 25 * self.Ilosc.i[ self.Structs["trade"][4] ]
            self.Economy.metal += 20 * self.Ilosc.i[ self.Structs["mine"][4] ]

            self.nexttick = pygame.time.get_ticks()+1000
            
        self.Economy.energy = 10 * self.Ilosc.i[ self.Structs["gene"][4] ]   
        self.Economy.energyMax = 10 * self.Ilosc.i[ self.Structs["gene"][4] ]
        for x in self.Structs:
            self.Economy.energy -= self.Ilosc.i[ self.Structs[x][4] ]  * self.Structs[x][2]
            
    def action(self, act, pos):
        if act == "None":
            return
        try:
            self.screen.blit(img(structures.structs[act][5]+"/"+act+"1.png"), pos)
        except:
            try:
                self.screen.blit(img(units.units[act][5]+"/"+act+"1.png"), pos)
            except:
                print "action() in main.py: "+act+" doesn't exist"
                exit()

    def mouse(self, button, pos):
        #oh my invisible unicorn, its madness that i have to do own delay
        if button[0] and self.nextpress <= pygame.time.get_ticks():
            for zz in funcs.pmenu:
                if pygame.Rect.collidepoint(zz, pos):
                    self.operation = constr(self.stage)[funcs.pmenu.index(zz)][2]
                    self.stage = constr(self.stage)[funcs.pmenu.index(zz)][3]
            #not UI   
            if pos[1] < sd.scrheight-256 and pos[1] > 20:  
                #placing units/buildings
                if not self.operation == "None":
                    try:
                        if self.Economy.credits >= self.Units[self.operation][0] and self.Economy.metal >= self.Units[self.operation][1]:
                            self.updateUs.add(classes.Unit(self.operation, self.lastid, self.Units[self.operation][3], self.Units[self.operation][5], (pos[0]+self.cam.x, pos[1]+self.cam.y), 1))
                            self.Ilosc.u[self.Units[self.operation][4]] += 1
                            self.Economy.credits -= self.Units[self.operation][0]
                            self.Economy.metal -= self.Units[self.operation][1]
                    except:
                        if self.Economy.credits >= self.Structs[self.operation][0] and self.Economy.metal >= self.Structs[self.operation][1]:
                            self.updateUs.add(classes.Unit(self.operation, self.lastid, self.Structs[self.operation][3], self.Structs[self.operation][5], (pos[0]+self.cam.x, pos[1]+self.cam.y), 0))
                            self.Ilosc.i[self.Structs[self.operation][4]] += 1
                            self.Economy.credits -= self.Structs[self.operation][0]
                            self.Economy.metal -= self.Structs[self.operation][1]

                    self.lastid += 1
                else:
                    pass

            self.nextpress = pygame.time.get_ticks()+200
        elif button[2]:
            self.operation = "None"  
            self.selected = list()         
        #info
        else:
            for zz in funcs.pmenu:
                if pygame.Rect.collidepoint(zz, pos):
                    nameofunit = assets.constr(self.stage)[funcs.pmenu.index(zz)][2]
                    if not nameofunit == "None":
                        try:
                            cost = " - Crystal: "+str(self.Units[nameofunit][0])+" Metal: "+str(self.Units[nameofunit][1])
                        except:
                            cost = " - Crystal: "+str(self.Structs[nameofunit][0])+" Metal: "+str(self.Structs[nameofunit][1])
                    else:
                        cost = ""
                    printsur(11, assets.constr(self.stage)[funcs.pmenu.index(zz)][0]+cost, [240, 240, 255], "center", (sd.scrwidth/2, sd.scrheight-256+128), self.screen)
                    #print "true satanic info"
            
    def events(self):
        evl = pygame.event.get()
        for ev in evl:
            if ev.type == QUIT:
                pygame.quit()
                sys.exit()
            elif ev.type == KEYDOWN:
                if ev.key == K_q:
                    pygame.quit()
                    sys.exit()
            elif ev.type == MOUSEBUTTONDOWN and self.postmp[0] == -1:
                if not pygame.key.get_pressed()[K_LCTRL]:
                    self.selected = list()
                self.postmp = pygame.mouse.get_pos()
            elif ev.type == MOUSEBUTTONUP:
                self.postmp = (-1,-1)
                    
        if not self.postmp[0] == -1 and pygame.mouse.get_pos()[1] < 635 and self.postmp[1] < 635:
            self.SelectInRect(pygame.mouse.get_pos())
        self.mouse(pygame.mouse.get_pressed(), pygame.mouse.get_pos())
        self.action(self.operation, pygame.mouse.get_pos())
        #-------------------------camera move---------------------------            
        key = pygame.key.get_pressed()
        if key[K_UP]:
            self.cam.update("n")
        if key[K_DOWN] and self.cam.y+768+15 <= self.terrain.ym:
            self.cam.update("s")
        if key[K_LEFT]:
            self.cam.update("w")
        if key[K_RIGHT] and self.cam.x+1024+15 <= self.terrain.xm:
            self.cam.update("e")
                    
                    

    def tick(self):
        
        self.terrain.draw(self.screen, self.cam.x, self.cam.y) 
        self.updateUs.update(self.screen, self.cam.x, self.cam.y)
        """self.DrawObj()"""
        self.DrawHolo()
        self.DrawUI()
        self.EcoTick()
        self.events()
        
        pygame.display.update()
        

    def loop(self):
        while 1:
            self.tick()
            self.czas.tick(50)
        return 0
        

Main()
